import sys
import os
from flask import Flask, request, send_file, jsonify
from utils import ArgumentParser, ConfigLoader, LOG
from model import OpenAIModel
from translator import PDFTranslator

app = Flask(__name__)

# 定义临时文件目录
TEMP_FILE_DIR = "flask_temps/"

# 确保临时文件目录存在
if not os.path.exists(TEMP_FILE_DIR):
    os.makedirs(TEMP_FILE_DIR)

@app.route('/translation', methods=['POST'])
def translation():
    try:
        input_file = request.files['input_file']
        target_language = request.form.get('target_language', 'Chinese')

        LOG.debug(f"[input_file]\n{input_file}")
        LOG.debug(f"[input_file.filename]\n{input_file.filename}")

        if input_file and input_file.filename:
            # 创建临时文件路径
            input_file_path = os.path.join(TEMP_FILE_DIR, input_file.filename)
            LOG.debug(f"[input_file_path]\n{input_file_path}")

            input_file.save(input_file_path)

            # 调用翻译函数
            output_file_path = Translator.translate_pdf(
                pdf_file_path=input_file_path,
                target_language=target_language
            )

            # 构造完整的文件路径
            output_file_path = os.path.join(os.getcwd(), output_file_path)
            LOG.debug(f"[output_file_path]\n{output_file_path}")

            # 返回翻译后的文件
            return send_file(output_file_path, as_attachment=True)
    except Exception as e:
        response = {
            'status': 'error',
            'message': str(e)
        }
        return jsonify(response), 400


def initialize_translator():
    # 解析命令行
    argument_parser = ArgumentParser()
    args = argument_parser.parse_arguments()
    
    # 加载配置
    config_loader = ConfigLoader(args.config)
    config = config_loader.load_config()

    # 设置模型参数
    model_name = args.openai_model if args.openai_model else config['OpenAIModel']['model']
    api_key = args.openai_api_key if args.openai_api_key else config['OpenAIModel']['api_key']
    model = OpenAIModel(model=model_name, api_key=api_key)

    # 实例化 PDFTranslator 类
    global Translator
    Translator = PDFTranslator(model)


if __name__ == "__main__":
    # 初始化 translator
    initialize_translator()
    # 启动 Flask Web Server
    app.run(host="0.0.0.0", port=5000, debug=True)